package com.wva.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wva.common.status.StatusEnum;
import com.wva.common.status.Status;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class R<T> implements Status {
    private int code;
    private String message;
    private T data;

    public R(Status status) {
        code = status.getCode();
        message = status.getMessage();
    }

    public static R<Object> ok() {
        return new R<>(StatusEnum.OK.getCode(), StatusEnum.OK.getMessage(), null);
    }

    public static <T> R<T> ok(T data) {
        return new R<>(StatusEnum.OK.getCode(), StatusEnum.OK.getMessage(), data);
    }

    public static R<Object> err(String message) {
        return new R<>(StatusEnum.ERROR.getCode(), message, null);
    }

    public R<T> code(int status) {
        this.code = status;
        return this;
    }

    public R<T> message(String message) {
        this.message = message;
        return this;
    }

    public R<T> data(T data) {
        this.data = data;
        return this;
    }

    public String toJson() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            return "{\"code\":1, \"message\":\"未知错误\"}";
        }
    }
}
